// get_user_data
// get_post_list_by_user
const getUserData = {
    taskConfig: { taskStatus: false },
    saveUserInfo: {},
    setting: {},
    postViewList: [],
    data: {},
    tipContent: { get_user_data: '收集用户数据', get_post_list_by_user: '红薯号采集笔记列表' },
    watchValue(key, newVal) {
        if (key == 'taskStatus' && newVal) {
            if (getUserData.data.skey == 'get_post_list_by_user') {
                newVal = {
                    collect_id: getUserData.data.setting.collect_id || '',
                    post: getUserData.saveUserInfo.post_list
                }
                getUserData.saveUserInfo = newVal
            }
            console.log('收集的用户数据：' + JSON.stringify(getUserData.saveUserInfo));
            Xhs.taskConfig.taskStatus = true
        }
        if (key == 'errorTask' && newVal) {
            let skey = getUserData.data.skey
            let params = {
                taskType: skey,
                task_id: getUserData.data.task_id,
                taskName: getUserData.tipContent[skey],
                errorTip: newVal,
                taskData: getUserData.getOptions,
                taskDate: Comman.getDate()
            }
            Xhs.errorTask(params)
            getUserData.taskConfig.taskStatus = true
        }
    },
    init(data) {
        getUserData.setting = data.setting || {}
        getUserData.data = data
        getUserData.postViewList = []
        getUserData.saveUserInfo = {}
        getUserData.taskConfig = Comman.defineReactive(
            {
                taskStatus: false,
                errorTask: '',
            },
            '',
            getUserData.watchValue
        )
        getUserData.openTask()
    },
    start(data) {
        //初始化数据
        getUserData.init(data)
    },
    openTask() {
        let homeMnue = btnConfig.home.homeMnue
        let homeBtn = btnConfig.home.homeBtn
        let searchIconBtn = btnConfig.home.searchIconBtn
        //重置首页
        while (!depth(homeMnue.options.depth).id(homeMnue.options.id).exists()) {
            back();
            console.log('back...');
            sleep(2000);
        }
        //点击首页
        let nowHomeBtn = homeBtn.default()
        if (!nowHomeBtn) {
            console.log('首页按钮不存在，请检查并手动复原首页重新启动');
            getUserData.taskConfig.errorTask = '首页按钮不存在'
            return
        }
        if (nowHomeBtn.bounds) {
            App.clickByBtn(nowHomeBtn, 3)
        } else {
            App.click(homeBtn.position.x, homeBtn.position.y, 3)
        }
        //点击搜索图标按钮
        let nowSearchIconBtn = searchIconBtn.default()
        if (!nowSearchIconBtn) {
            console.log('搜索图片不存在，并手动复原重新启动');
            getUserData.taskConfig.errorTask = '搜索图片不存在'
            return
        }
        if (nowSearchIconBtn.bounds) {
            App.clickByBtn(nowSearchIconBtn, 3)
        } else {
            App.click(searchIconBtn.position.x, searchIconBtn.position.y, 3)
        }
        if (getUserData.data.skey == 'get_user_data' && !getUserData.setting.xhsid) {
            if (!myUi.deviceInfo.xhsid) {
                console.log('未配置采集内容，反馈异常');
                getUserData.taskConfig.errorTask = '未配置采集内容'
                return
            }
            getUserData.searUser(myUi.deviceInfo.xhsid)
            return
        }
        if (getUserData.data.skey !== 'get_user_data' && !getUserData.setting.collect_content) {
            console.log('未配置采集内容，反馈异常');
            getUserData.taskConfig.errorTask = '未配置采集内容'
            return
        }
        getUserData.searUser(getUserData.setting.collect_content || getUserData.setting.xhsid)
    },
    searUser(xhsId) {
        let searchBtn = btnConfig.search.searchBtn
        let searchTabBtn = btnConfig.search.searchTabBtn
        setText(0, '')
        sleep(1000)
        setText(0, xhsId)
        App.randomSleep(2, 4)
        //点击搜索按钮
        let nowSearchBtn = searchBtn.default()
        if (!nowSearchBtn) {
            console.log('搜索按钮不存在，请检查并手动复原重新启动');
            getUserData.taskConfig.errorTask = '搜索按钮不存在'
            return
        }
        if (nowSearchBtn.bounds) {
            App.clickByBtn(nowSearchBtn, 3)
        } else {
            App.click(searchBtn.position.x, searchBtn.position.y, 3)
        }
        //切换到用户标签页
        let searchTab = searchTabBtn.default()
        if (!searchTab.length) {
            console.log('未查询到切换按钮，反馈异常')
            getUserData.taskConfig.errorTask = '未查询到切换按钮'
            return
        }
        searchTab.forEach(element => {
            let userBtn = element.findOne(text('用户'))
            let userBtn2 = element.findOne(text('账号'))
            if (userBtn) {
                App.clickByBtn(userBtn, 2)
            }
            if (userBtn2) {
                App.clickByBtn(userBtn2, 2)
            }
        });
        App.randomSleep(2, 4)
        getUserData.getUserInfo()
    },
    getUserInfo() {
        console.log('getUserInfo');
        let userImgBtn = btnConfig.search.searchUserImg.default()
        if (userImgBtn.length) {
            App.clickByBtn(userImgBtn[0], true)
            let data = getUserData.data
            let endTime = data.time[1] * 1000
            let nowTime = new Date().getTime()
            console.log('活动结束日期：', new Date(endTime).toLocaleDateString() + new Date(endTime).toLocaleTimeString());
            if (data.skey == 'get_post_list_by_user') {
                getUserData.getPostInfo({
                    collect_id: data.setting.collect_id || '',
                    post_list: []
                }, data.setting.num)
                return
            }
            let userNick = btnConfig.user.userPageNick.default()
            let like = btnConfig.user.userPagelike.default()
            let userPageAge = btnConfig.user.userPageAge.default()
            let userId = btnConfig.user.userPageId.default()
            let closeBtn = id('dbb').findOne(2000)
            // let follow = btnConfig.user.userPagefollow.default()
            // let fans = btnConfig.user.userPagefans.default()
            // let userLocation = btnConfig.user.userPageLocation.default()
            if (closeBtn) {
                App.clickByBtn(closeBtn, 3)
            }
            if (userId) {
                let userInfo = {
                    count_id: data.setting.count_id || '',
                    xhsid: userId ? userId.text().replace('小红书号：', '') : '',
                    nickname: userNick ? userNick.text() : '',
                    look_num: 0,
                    like_num: 0,
                    save_num: 0,
                    post_num: 0,
                    comment_num: 0,
                    avg_look_num: userPageAge ? userPageAge.text() : 0,
                    post_list: []
                }
                if (like) {
                    App.clickByBtn(like, 3)
                    let AllPush = btnConfig.user.userAllPush.default()
                    let AllLike = btnConfig.user.userAllLike.default()
                    let Allsave = btnConfig.user.userAllSave.default()
                    userInfo['like_num'] = AllLike ? AllLike.text() : 0
                    userInfo['save_num'] = Allsave ? Allsave.text() : 0
                    userInfo['post_num'] = AllPush ? AllPush.text() : 0
                    if (AllLike || Allsave || AllPush) {
                        back()
                    }
                }
                console.log('userInfo', userInfo);
                sleep(2000)
                getUserData.getPostInfo(userInfo)
            } else {
                console.log('回复任务：报错--无法获取用户信息');
                getUserData.taskConfig.errorTask = '无法获取用户信息'
            }
            sleep(2000)
            back()
            sleep(2000)
        } else {
            console.log('回复任务：报错--无法获取用户头像按钮');
            getUserData.taskConfig.errorTask = '无法获取用户头像按钮'
        }
        sleep(2000)
    },
    getPostInfo(userInfo, listNum) {
        console.log('getPostInfo');
        let endTime = getUserData.data.time[1] * 1000 - 30000
        let nowTimeTask = new Date().getTime()
        let allSearchInfo = userInfo
        let postList = btnConfig.user.userPostList.default()
        if(endTime <= nowTimeTask || getUserData.taskConfig.taskStatus){
            console.log('已到任务结束时间');
            getUserData.saveUserInfo = allSearchInfo
            if (!getUserData.taskConfig.taskStatus) {
                getUserData.taskConfig.taskStatus = true
            }
            return
        }
        if (!postList) {
            console.log('未查询到帖子列表，反馈异常')
            allSearchInfo.post_list = []
            getUserData.taskConfig.taskStatus = true
            return
        }
        let postItems = btnConfig.user.userPostItems.default()
        if (!postItems.length) {
            console.log('未查询到帖子，反馈异常')
            allSearchInfo.post_list = []
            getUserData.taskConfig.taskStatus = true
            return
        }
        postItems.forEach((postView, index) => {
            let nowTime = new Date().getTime()
            if (listNum && listNum <= allSearchInfo.post_list.length || endTime <= nowTime) {
                console.log(endTime <= nowTime ? '任务超时，进行结束':'帖子收集完毕')
                getUserData.saveUserInfo = allSearchInfo
                if (!getUserData.taskConfig.taskStatus) {
                    getUserData.taskConfig.taskStatus = true
                }
                return
            }

            let postDesc = postView.desc() || ''
            let like = postView.findOne(id('jfa'))
            let viewNum = postView.findOne(id('a3q'))
            if ((!like || like.text() == '赞') && getUserData.data.setting.like_min * 1 > 0) {
                console.log('赞数不满足门槛，跳过此笔记');
                // 不满足赞数门槛
                return
            }
            console.log('NO：' + index + '当前帖子：' + postDesc);
            if (getUserData.postViewList.findIndex(item => item == postDesc) == -1) {
                getUserData.postViewList.push(postDesc)
                getUserData.resolvePost(postView, allSearchInfo, postDesc,viewNum)
            }
        });
        if (listNum && listNum <= allSearchInfo.post_list.length) {
            console.log('帖子收集完毕')
            getUserData.saveUserInfo = allSearchInfo
            if (!getUserData.taskConfig.taskStatus) {
                getUserData.taskConfig.taskStatus = true
            }
            return
        }
        //循环后滚动帖子列表查看更多帖子信息
        if (!postList.scrollable()) {
            console.log('帖子列表到底了-无其他帖子了')
            getUserData.saveUserInfo = allSearchInfo
            if (!getUserData.taskConfig.taskStatus) {
                getUserData.taskConfig.taskStatus = true
            }
            return
        }
        if (postList.scrollForward()) {
            console.log('帖子列表滚动成功')
            App.randomSleep(2, 4)
            getUserData.getPostInfo(allSearchInfo, listNum)
        } else {
            getUserData.saveUserInfo = allSearchInfo
            getUserData.taskConfig.taskStatus = true
        }
    },
    resolvePost(postView, allSearchInfo, title,viewNum) {
        console.log('resolvePost');
        App.clickByBtn(postView, true)
        let infoDom = btnConfig.post.contentInfo.default(true)
        let infoDom2 = btnConfig.post.contentInfo2.default(true)
        let titleDom = btnConfig.post.titleInfo.default(true)
        let likeDom = className('android.widget.Button').descContains('点赞').find()
        let saveDom = className('android.widget.Button').descContains('收藏').find()
        let commentDom = className('android.widget.Button').descContains('评论').find()

        let targetSave = (getUserData.data.setting.save_min || 0) * 1
        let targeComment = (getUserData.data.setting.comment_min || 0) * 1
        let targetLike = (getUserData.data.setting.like_min || 0) * 1

        sleep(3000)
        let shareBrn = btnConfig.post.shareBrn.default() || btnConfig.post.moreBtn.default()
        if (commentDom.length) {
            let nowIndex = commentDom.length > 2 ? 1 : 0;
            let postInfo = {
                link: "",
                title: titleDom.length ? titleDom[nowIndex].text() : title,
                content: infoDom.length ? infoDom[nowIndex].text() : infoDom2.length ? infoDom2[nowIndex].desc() : '',
                like_num: likeDom.length ? likeDom[nowIndex].desc().split('点赞')[1] * 1 : 0,
                save_num: saveDom.length ? saveDom[nowIndex].desc().split('收藏')[1] * 1 : 0,
                comment_num: commentDom.length ? commentDom[nowIndex].desc().split('评论')[1] * 1 : 0,
                view_num:viewNum && viewNum.text ? viewNum.text() : 0
            }
            if (postInfo.save_num >= targetSave && postInfo.comment_num >= targeComment && postInfo.like_num >= targetLike) {
                console.log('满足条件帖子，开始收集');
                if (getUserData.data.skey == 'get_post_list_by_user') {
                    postInfo['send_time'] = ''
                    postInfo['comments'] = []
                } else {
                    postInfo['send_date'] = ''
                }
                getUserData.getLinke(shareBrn, postInfo)
                allSearchInfo.post_list.push(postInfo)
            }
        }
        App.randomSleep(2, 4)
        back()
        sleep(2000)
    },
    getLinke(shareBrn, postInfo) {
        console.log('getLinke');
        if (shareBrn) {
            App.clickByBtn(shareBrn, 3)
            let moreBtnMenu = btnConfig.post.moreBtnMenu.default()
            let copyBtn = btnConfig.post.copyBtn.default()
            if (!moreBtnMenu) {
                console.log('找不到moreBtnMenu');
            }
            if (!copyBtn) {
                let scroll = true
                while (!copyBtn && scroll) {
                    try {
                        scroll = moreBtnMenu.scrollForward()
                        sleep(2000)
                        copyBtn = btnConfig.post.copyBtn.default()
                        sleep(2000)
                    } catch (error) {
                        scroll = false
                    }
                }
                if (!copyBtn) {
                    console.log('找不到复制链接按钮');
                }
            }

            if (copyBtn.bounds) {
                App.clickByBtn(copyBtn, true)
            } else {
                App.click(btnConfig.post.copyBtn.position.x, btnConfig.post.copyBtn.position.y, true)
            }
            // launch(Xhs.AppPackName)
            // sleep(1000)
            // postInfo['link'] = getClip() || ''
            // sleep(3000)
            // launch(Xhs.packName);

            let resolveInputBtn = btnConfig.post.resolveInputBtn.default()
            if (resolveInputBtn) {
                App.clickByBtn(resolveInputBtn, 3)
                let input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                if (input) {
                    input.paste()
                    App.randomSleep(2, 4)
                    input = btnConfig.post.resolveInput.default() || btnConfig.post.resolveInput2.default()
                    postInfo['link'] = input ? input.text() : '查询文章链接失败'
                    setText('')
                    sleep(1000)
                    back()
                }
                sleep(2000)
            } else {
                console.log('找不到输入框');
            }
        } else {
            console.log('找不到分享按钮');
        }
    },
}
module.exports = getUserData